Telegram Group & Telegram Channel
Java 25: новый формат конструктора

Сегодня расскажу про новую фичу в осенней джаве. Суть простая - this и super не обязательно должны идти первой строкой в конструкторе.

Зачем это нужно? Чтобы упростить валидацию.

Сейчас, чтобы добавить проверку аргументов, приходится оборачивать аргументы в методы:
class Employee extends Person {
  private static int verifyAge(int value) {
  if (age < 18)
    throw new IllegalArgumentException(...);
    return value;
  }

  Employee(int age) {
     super(verifyAge(age));
  }
}


С новым JEP эти костыли не нужны, нужные проверки пишем в начале конструктора:
class Employee extends Person {
  Employee(int age) {
  if (age < 18)
   throw new IllegalArgumentException(...);
  super(age);
  }
}


Области кода вокруг this/super называются очень литературно: пролог и эпилог🥰
public Person {
   // prologue
   super();
   // epilogue
}

В пролог нельзя вставить любой код:
Нельзя обращаться к переменным родителя
Нельзя вызывать нестатические методы
Нельзя вызвать return
Можно присвоить поля текущего класса

Особо не разгуляешься, всё же основной сценарий фичи — валидация входных параметров.

Ещё из интересного:

1️⃣ В JVM не пришлось ничего менять

Потому что правила "this обязательно первый" в JVM нет. Это ограничение только на уровне языка, чтобы упростить работу компилятора:)

2️⃣ Меняется ответ на частый собесный вопрос "в каком порядке инициализируются переменные". Раньше порядок для нестатических полей был такой:

Поля Parent - Конструктор Parent - Поля Child - Конструктор Child

В Java 25 поля наследника можно инициализировать ДО вызова конструктора родителя:
Employee(int age, String officeID) {
   this.officeID = officeID;
   super(age);
}

Общая схема с этими прологами-эпилогами очень усложняется.

3️⃣ Фича называется Flexible Constructor Bodies. Я не смогла придумать адекватный перевод, поэтому очень интересно, как её переведут в статьях-обзорах:)



tg-me.com/java_fillthegaps/626
Create:
Last Update:

Java 25: новый формат конструктора

Сегодня расскажу про новую фичу в осенней джаве. Суть простая - this и super не обязательно должны идти первой строкой в конструкторе.

Зачем это нужно? Чтобы упростить валидацию.

Сейчас, чтобы добавить проверку аргументов, приходится оборачивать аргументы в методы:

class Employee extends Person {
  private static int verifyAge(int value) {
  if (age < 18)
    throw new IllegalArgumentException(...);
    return value;
  }

  Employee(int age) {
     super(verifyAge(age));
  }
}


С новым JEP эти костыли не нужны, нужные проверки пишем в начале конструктора:
class Employee extends Person {
  Employee(int age) {
  if (age < 18)
   throw new IllegalArgumentException(...);
  super(age);
  }
}


Области кода вокруг this/super называются очень литературно: пролог и эпилог🥰
public Person {
   // prologue
   super();
   // epilogue
}

В пролог нельзя вставить любой код:
Нельзя обращаться к переменным родителя
Нельзя вызывать нестатические методы
Нельзя вызвать return
Можно присвоить поля текущего класса

Особо не разгуляешься, всё же основной сценарий фичи — валидация входных параметров.

Ещё из интересного:

1️⃣ В JVM не пришлось ничего менять

Потому что правила "this обязательно первый" в JVM нет. Это ограничение только на уровне языка, чтобы упростить работу компилятора:)

2️⃣ Меняется ответ на частый собесный вопрос "в каком порядке инициализируются переменные". Раньше порядок для нестатических полей был такой:

Поля Parent - Конструктор Parent - Поля Child - Конструктор Child

В Java 25 поля наследника можно инициализировать ДО вызова конструктора родителя:
Employee(int age, String officeID) {
   this.officeID = officeID;
   super(age);
}

Общая схема с этими прологами-эпилогами очень усложняется.

3️⃣ Фича называется Flexible Constructor Bodies. Я не смогла придумать адекватный перевод, поэтому очень интересно, как её переведут в статьях-обзорах:)

BY Java: fill the gaps


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/java_fillthegaps/626

View MORE
Open in Telegram


Java: fill the gaps Telegram | DID YOU KNOW?

Date: |

Telegram and Signal Havens for Right-Wing Extremists

Since the violent storming of Capitol Hill and subsequent ban of former U.S. President Donald Trump from Facebook and Twitter, the removal of Parler from Amazon’s servers, and the de-platforming of incendiary right-wing content, messaging services Telegram and Signal have seen a deluge of new users. In January alone, Telegram reported 90 million new accounts. Its founder, Pavel Durov, described this as “the largest digital migration in human history.” Signal reportedly doubled its user base to 40 million people and became the most downloaded app in 70 countries. The two services rely on encryption to protect the privacy of user communication, which has made them popular with protesters seeking to conceal their identities against repressive governments in places like Belarus, Hong Kong, and Iran. But the same encryption technology has also made them a favored communication tool for criminals and terrorist groups, including al Qaeda and the Islamic State.

Should You Buy Bitcoin?

In general, many financial experts support their clients’ desire to buy cryptocurrency, but they don’t recommend it unless clients express interest. “The biggest concern for us is if someone wants to invest in crypto and the investment they choose doesn’t do well, and then all of a sudden they can’t send their kids to college,” says Ian Harvey, a certified financial planner (CFP) in New York City. “Then it wasn’t worth the risk.” The speculative nature of cryptocurrency leads some planners to recommend it for clients’ “side” investments. “Some call it a Vegas account,” says Scott Hammel, a CFP in Dallas. “Let’s keep this away from our real long-term perspective, make sure it doesn’t become too large a portion of your portfolio.” In a very real sense, Bitcoin is like a single stock, and advisors wouldn’t recommend putting a sizable part of your portfolio into any one company. At most, planners suggest putting no more than 1% to 10% into Bitcoin if you’re passionate about it. “If it was one stock, you would never allocate any significant portion of your portfolio to it,” Hammel says.

Java: fill the gaps from fr


Telegram Java: fill the gaps
FROM USA